package gggameserver.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class GGUtil {

	public static Process exec(String[] cmd, File dir) throws IOException {
		ArrayList cmdarray = new ArrayList();
		for (int i = 0; i < cmd.length; i++)
			cmdarray.add(cmd[i]);
		return exec(cmdarray, dir);
	}

	public static Process exec(ArrayList cmdarray, File dir) throws IOException {
		String[] pref = { "cmd", "/C" };

		if (!GGConfiguration.isWindows())
			pref = new String[0];

		String[] cmd = new String[pref.length + cmdarray.size()];
		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < pref.length; i++) {
			cmd[i] = pref[i];
			sb.append(cmd[i]);
			sb.append(" ");
		}

		for (int i = 0; i < cmdarray.size(); i++) {
			cmd[i + pref.length] = (String) cmdarray.get(i);
			sb.append(cmd[i + pref.length]);
			sb.append(" ");
		}

		System.out.println("> " + sb);
		return Runtime.getRuntime().exec(cmd, null, dir);
	}

	public static String collectOutput(Process p) throws IOException {
		// http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
		StringBuilder sb = new StringBuilder();

		// any error message?
		StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(),
				"ERR", sb);

		// any output?
		StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(),
				"OUT", sb);

		// kick them off
		errorGobbler.start();
		outputGobbler.start();

		waitFor(p);
		return sb.toString();
	}

	public static void waitFor(Process p) {
		boolean done = false;
		while (!done) {
			try {
				p.waitFor();
				done = true;
			} catch (InterruptedException e) {
			}
		}
	}

	public static ArrayList getFileList(File dir) {
		ArrayList filenames = new ArrayList();
		return getFilenameList(dir, "", filenames);
	}

	private static ArrayList getFilenameList(File dir, String dir_name,
			ArrayList filenames) {
		File[] dir_files = dir.listFiles();
		if (!dir_name.isEmpty())
			dir_name = dir_name + "/"; // TODO File.separatorChar;
		for (int i = 0; i < dir_files.length; i++) {
			File f = dir_files[i];
			String name = dir_name + f.getName();
			if (f.isDirectory())
				getFilenameList(f, name, filenames);
			else
				filenames.add(name);
		}
		return filenames;
	}

	public static ArrayList filterFiles(ArrayList filenames, String[] extensions) {
		ArrayList good_files = new ArrayList();
		for (int i = 0; i < filenames.size(); i++) {
			String name = ((String) filenames.get(i));
			String name_low = name.toLowerCase();
			for (int e = 0; e < extensions.length; e++)
				if (name_low.endsWith(extensions[e])) {
					good_files.add(name);
					break;
				}
		}
		return good_files;
	}

	static public boolean deleteDirectory(File path) {
		if (path.exists()) {
			File[] files = path.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory())
					deleteDirectory(files[i]);
				else
					files[i].delete();
			}
		}
		return path.delete();
	}

	public static void sleep(long millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			// TODO log.warn("Exception while sleeping", e);
		}
	}

	public static ArrayList getUnzipCommandline(String filename) {
		ArrayList cmdarray = new ArrayList();
		if (isWindows()) {
			cmdarray.add(new File(".", "7z").getAbsolutePath());
			cmdarray.add("x");
			cmdarray.add("-tzip");
			cmdarray.add(filename);
		} else {
			cmdarray.add("unzip");
			cmdarray.add(filename);
		}

		return cmdarray;
	}

	public static String toCmdline(ArrayList<String> cmdline) {
		StringBuilder sb = new StringBuilder();
		for (String arg : cmdline) {
			if (sb.length() != 0)
				sb.append(" ");

			if (arg.equals("~") || arg.equals(";") || arg.equals("*")
					|| arg.equals("$?")) {
				sb.append(arg);
			} else {
				sb.append("\'");
				sb.append(arg.replace("'", "'\\''"));
				sb.append("\'");
			}
		}
		return sb.toString();
	}

	public static boolean isWindows() {
		return System.getProperty("os.name").startsWith("Windows");
	}

}
